#include "udp.h"
#include "queue.h"

int main(int argc, char *argv[])
{
    int fd, numbytes;
    char recvbuf[DATA_MAXSIZE];
    char data[DATA_MAXSIZE];
    struct hostent *host;
    struct sockaddr_in server,client;

    MSG sendmsg;

    if (argc != 3) 
    {                              
        printf("Usage: %s, please input valid parameter!!! \n",argv[0]);
        exit(1);
    }

    if ((host = gethostbyname(argv[1])) == NULL)
    { 
        printf("gethostbyname() error\n");
        exit(1);
    }

    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        printf("socket() error\n");
        exit(1);
    }

    bzero(&server,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));                          /* htons() is needed again */
    server.sin_addr = *((struct in_addr *)host -> h_addr);          /* host->h_addr passes "*host"'s info to "h_addr" */

    socklen_t len = sizeof(struct sockaddr_in);

    int counter = 0;
    while (1)
    {
        printf("input message:");
        memset(&sendmsg, 0, sizeof(sendmsg));
        memset(recvbuf, 0, sizeof(recvbuf));
        fgets(data, 40, stdin);
        data[strlen(data) - 1] = '\0';
        if(!strncmp(data, "exit", 4))    break;

        time_t t;  
        time(&t);  
        sendmsg.id = counter++;
        strcpy(sendmsg.time, ctime(&t));
        strncpy(sendmsg.data, data, strlen(data));
        sendmsg.lengh = strlen(sendmsg.data);
        
        sendto(fd, (char*)&sendmsg, sizeof(sendmsg), 0, (struct sockaddr *)&server, len);

        if ((numbytes = recvfrom(fd, recvbuf, DATA_MAXSIZE, 0, (struct sockaddr *)&server, &len)) == -1)
        {
            printf("recvfrom() error\n");
            exit(1);
        }

        recvbuf[numbytes] = '\0';
        printf("Server Return Reverse Message: %s\n", recvbuf);
    }

    close(fd);
    return 0;
}